
package com.netease.xone.fragment;

import protocol.XoneCallBack;
import protocol.XoneService;
import protocol.meta.Source;
import protocol.meta.Subject;
import protocol.meta.User;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.X1LoadingAdapterViewBase.OnLoadingListener;
import com.netease.pkgRelated.XoneConsts;
import com.netease.xone.R;
import com.netease.xone.activity.ActivityEditProfile;
import com.netease.xone.activity.ActivityFansList;
import com.netease.xone.adapter.ExpandSubjectAdapter;
import com.netease.xone.fragment.FragmentFansList.FansListType;
import com.netease.xone.widget.LoadingImageView;
import com.netease.xone.widget.listview.ExpandableAdapterWrapper;
import com.netease.xone.widget.listview.LoadingExpandableListView;
import com.netease.xone.widget.listview.MultiExpandableAdapterManager;
import com.netease.xone.widget.tabview.AbsTabView.OnTabSelectListener;
import com.netease.xone.widget.tabview.ProfileTab;

import db.manager.ManagerAccount;

public class FragmentProfile extends FragmentBase {

    public static FragmentProfile newInstance(boolean isSelf) {
        FragmentProfile fragment = new FragmentProfile();
        Bundle b = new Bundle();
        b.putBoolean(XoneConsts.BUNDLE_KEY.PROFILE_IS_SELF, isSelf);
        fragment.setArguments(b);
        return fragment;
    }

    // View
    private LoadingExpandableListView mList;
    private TextView mNameText; // 用户名
    private TextView mFocusCountText;// 关注数，我的主页
    private TextView mFansCountText;// 粉丝数，我的主页
    private ProfileTab mTab;
    private ExpandSubjectAdapter mAdapter;
    private MultiExpandableAdapterManager mMultiAdapterMgr;
    private LoadingImageView mAvatarImage;
    // data
    private User mUser;
    private boolean mIsSelf;// 标识当前是个人主页还是他人主页
    // Tid
    private int mUserDetailTid;
    private int mSubscribeTid;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mIsSelf = getArguments().getBoolean(XoneConsts.BUNDLE_KEY.PROFILE_IS_SELF);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_profile, null);
        mList = (LoadingExpandableListView)view.findViewById(R.id.loading_expandable_list);
        mList.disablePullToRefresh();
        // Header
        View header = inflater.inflate(R.layout.view_profile_header, null);
        mAvatarImage = (LoadingImageView)header.findViewById(R.id.profile_avatar);
        mNameText = (TextView)header.findViewById(R.id.profile_name);
        View followContainer = header.findViewById(R.id.profile_follow_container);
        View fansContainer = header.findViewById(R.id.profile_fans_container);
        mFocusCountText = (TextView)header.findViewById(R.id.profile_focus_count);
        mFansCountText = (TextView)header.findViewById(R.id.profile_fans_count);
        followContainer.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                ActivityFansList.startActivity(getActivity(), ManagerAccount.getInstance()
                        .getCurrentAccountId(), FansListType.follow);
            }
        });

        fansContainer.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                ActivityFansList.startActivity(getActivity(), ManagerAccount.getInstance()
                        .getCurrentAccountId(), FansListType.fans);
            }
        });

        header.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if(mIsSelf){
                    ActivityEditProfile.startActivity(getActivity(), mUser);
                }else{
                    Toast.makeText(getActivity(), "他人主页", Toast.LENGTH_SHORT).show();
                }
            }
        });
        // Tab
        mTab = new ProfileTab(getActivity(), mIsSelf);
        mTab.create();// 手动创建
        mTab.setOnTabSelectListener(new OnTabSelectListener() {

            @Override
            public void onTabSelected(View tabView, int index) {
                mMultiAdapterMgr.setCurrentAdapter(index);
                switch (index) {
                    case 1:
                        mList.load();
                        break;
                }
            }

            @Override
            public void onTabReSelected(View tabView, int index) {

            }
        });

        mList.setOnLoadingListener(new OnLoadingListener() {

            @Override
            public void onRefreshing() {

            }

            @Override
            public void onLoading() {
                switch (mMultiAdapterMgr.getCurrentAdapterIndex()) {
                    case 1:
                        mSubscribeTid = XoneService.getInstance()
                                .doGetSubscribeList(
                                        Integer.valueOf(ManagerAccount.getInstance()
                                                .getCurrentAccountId()));
                        break;
                }
            }

            @Override
            public void onLoadingMore() {

            }

        });

        // add header
        mList.getRefreshableView().addHeaderView(header);
        mList.getRefreshableView().addHeaderView(mTab);
        // set adapter
        mMultiAdapterMgr = new MultiExpandableAdapterManager(mList);
        mAdapter = new ExpandSubjectAdapter(getActivity());

        mMultiAdapterMgr.addAdapter(new ExpandableAdapterWrapper(new TestAdapter()));
        mMultiAdapterMgr.addAdapter(mAdapter);
        mMultiAdapterMgr.addAdapter(new ExpandableAdapterWrapper(new TestAdapter()));
        mMultiAdapterMgr.addAdapter(new ExpandableAdapterWrapper(new TestAdapter()));
        mMultiAdapterMgr.addAdapter(new ExpandableAdapterWrapper(new TestAdapter()));

        mMultiAdapterMgr.setCurrentAdapter(0);

        // Service
        XoneService.getInstance().addListener(mCallBack);
        mUserDetailTid = XoneService.getInstance().doGetUserDetail(ManagerAccount.getInstance().getCurrentAccountId());
        return view;
    }

    private class TestAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return 50;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            TextView tv = new TextView(getActivity());
            tv.setText("Position:" + position);
            return tv;
        }

    }

    @Override
    public void onDestroyView() {
        XoneService.getInstance().removeListener(mCallBack);
        mAdapter.removeListener();
        super.onDestroyView();
    };

    XoneCallBack mCallBack = new XoneCallBack() {

//        @Override
//        public void onSourceListSubject(int transactionId,
//                java.util.List<protocol.meta.Subject> list) {
//            if (mSubscribeTid == transactionId) {
//                mAdapter.addAll(list);
//            }
//        };
//
//        @Override
//        public void onSourceListSubjectError(int transactionId, int errCode, String err) {
//            if (mSubscribeTid == transactionId) {
//                Toast.makeText(getActivity(), err, Toast.LENGTH_SHORT).show();
//            }
//        };

        @Override
        public void onGetSubscribeSubjectList(int transactionId,
                java.util.List<protocol.meta.Subject> subjectList) {
            if (mSubscribeTid == transactionId) {
                if(subjectList != null && subjectList.size() != 0){
                    mAdapter.clear();
                    mAdapter.addAll(subjectList);
                    mList.onLoadingComplete(false);
                }else{
                    mList.onNoContent();
                }
            }
        };

        @Override
        public void onGetSubscribeSubjectListError(int transactionId, int errCode, String err) {
            if(mSubscribeTid == transactionId){
                mList.onLoadingError();
            }
        };

        @Override
        public void onGetUserDetail(int transactionId, protocol.meta.User user) {
            if (mUserDetailTid == transactionId && user != null) {
                mUser = user;
                mAvatarImage.setImageResource(R.drawable.avatar_user_default_110);
                if(!TextUtils.isEmpty(mUser.avatar)){
                    mAvatarImage.setLoadingImage(mUser.avatar);
                }
                mNameText.setText(user.nickname);
                mTab.setCountText(0, user.infoCount);// 发布
                mTab.setCountText(1, user.subscribeCount);// 订阅
                mTab.setCountText(2, user.praiseCount);// 赞
                if (mIsSelf) {
                    // 我的主页
                    mTab.setCountText(3, user.commentCount);// 评论
                    mFocusCountText.setText(String.valueOf(user.focusCount));// 关注
                } else {
                    // 他人主页
                    mTab.setCountText(3, user.focusCount);// 关注
                }
                if (mIsSelf) {
                    // 我的主页
                    mTab.setCountText(4, 0);// 草稿
                    mFansCountText.setText(String.valueOf(user.fansCount));// 粉丝
                } else {
                    // 他人主页
                    mTab.setCountText(4, user.fansCount);// 粉丝
                }
            }
        };

        @Override
        public void onUnsubscribe(int transactionId, int sourceId) {

            // 更新订阅状态，这里针对整个主题下的资讯源都取消订阅的情况，删除该主题
            if (mIsSelf && mAdapter != null) {
                int subscribeCount = mTab.getCount(1);
                for (int i = 0; i < mAdapter.getGroupCount(); i++) {
                    Subject subject = mAdapter.getGroup(i);
                    if (subject.sourceList == null || subject.sourceList.size() == 0)
                        continue;// 忽略没有资讯源的主题
                    for (Source source : subject.sourceList) {
                        if (source.sourceId == sourceId) {
                            subscribeCount--;
                            break;
                        }
                    }
                    mTab.setCountText(1, subscribeCount);
                    if (subject.mySubCount == 0) {
                        mAdapter.removeGroup(subject);
                    }
                }
            }
        };

        @Override
        public void onSubscribe(int transactionId, int[] subjectIdAndSourceId) {
            // 更新订阅状态，这里针对用户之前未订阅该资讯源的主题的情况，重新获取订阅信息
            if (mIsSelf && mAdapter != null) {
                // 有订阅信息，需要更新订阅状态
                int sourceId = subjectIdAndSourceId[1];
                int subscribeCount = mTab.getCount(1);
                // 更新订阅状态
                boolean hasNewSubject = true;
                for (int i = 0; i < mAdapter.getGroupCount(); i++) {
                    Subject subject = mAdapter.getGroup(i);
                    if (subject.sourceList == null || subject.sourceList.size() == 0)
                        continue;
                    for (Source source : subject.sourceList) {
                        if (sourceId == source.sourceId) {
                            hasNewSubject = false;
                            subscribeCount++;
                        }
                    }
                }
                mTab.setCountText(1, subscribeCount);
                // 有新的订阅主题
                if (hasNewSubject) {
                    // 重新刷新订阅列表
                    mSubscribeTid = XoneService.getInstance().doGetSubscribeList(
                            Integer.valueOf(ManagerAccount.getInstance().getCurrentAccountId()));
                    // 重新刷新用户信息（订阅数）
                    mUserDetailTid = XoneService.getInstance().doGetUserDetail(ManagerAccount.getInstance().getCurrentAccountId());
                }
            }
        };

        @Override
        public void onFollow(int transactionId, String userId) {
            if (mIsSelf && mUser != null) {
                mUser.focusCount++;
                mFocusCountText.setText(String.valueOf(mUser.focusCount));// 关注
            }
        };

        @Override
        public void onCancelFollow(int transactionId, String userId) {
            if (mIsSelf && mUser != null) {
                mUser.focusCount--;
                mFocusCountText.setText(String.valueOf(mUser.focusCount));// 关注
            }
        };

        @Override
        public void onUpdateUser(int transactionId) {
            //更新用户数据
            mUserDetailTid = XoneService.getInstance().doGetUserDetail(ManagerAccount.getCurAccountId());
        };
    };
}
